# 视频人脸识别
import cv2
import dlib

# 加载人脸检测器
detector = dlib.get_frontal_face_detector()

cap = cv2.VideoCapture(0)
if not cap:
    print('cannot open camera')
    exit()
while True:
    # 逐帧捕获
    ret, frame = cap.read()
    # 如果正确读取帧，ret为True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # 我们在框架上的操作到这里
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 人脸检测
    faces = detector(gray)
    print(faces)
    # 绘制人脸框
    for face in faces:
        x, y, w, h = face.left(), face.top(), face.width(), face.height()
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # 显示结果帧e
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) == 27:
        break
# 完成所有操作后，释放捕获器
cap.release()
cv2.destroyAllWindows()